﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;

namespace OS.GenericDashboardViewer.Infrastructure
{
    public static class SerializeHelper
    {

        public static T DeserializeFromFile<T>(string filePath, params Type[] knownTypes)
        {

            FileStream fs = new FileStream(filePath,FileMode.Open);
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser = new DataContractSerializer(typeof(T), knownTypes);

            T deserializedObj =
                (T)ser.ReadObject(reader, true);
            reader.Close();
            fs.Close();

            return deserializedObj;
        }


        public static void SerializeToFile(object objToSer, string filePath, params Type[] knownTypes)
        {
            if (objToSer == null)
            {
                throw new NullReferenceException("objToSer");
            }

            DataContractSerializer serializer = new DataContractSerializer(objToSer.GetType(), knownTypes);
            FileStream writer = new FileStream(filePath, FileMode.OpenOrCreate);
            serializer.WriteObject(writer, objToSer);
            writer.Close();

        }

    }
}
